package com.junjie.checkin.handller.mybatis;

import com.junjie.checkin.entity.Enum.StringValuedEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 洪浚杰
 * @description
 * @date 2025/6/13 15:34
 */
public abstract class BaseStringEnumTypeHandler<E extends Enum<E> & StringValuedEnum>
        extends BaseTypeHandler<E> {

    private final Class<E> enumClass;

    public BaseStringEnumTypeHandler(Class<E> enumClass) {
        this.enumClass = enumClass;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Object value = rs.getObject(columnName);
        return fromObject(value);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Object value = rs.getObject(columnIndex);
        return fromObject(value);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object value = cs.getObject(columnIndex);
        return fromObject(value);
    }

    /**
     * 根据 ResultSet 中的对象判断类型并转换为枚举
     */
    private E fromObject(Object value) throws SQLException {
        if (value == null) {
            return null;
        }
        try {
            if (value instanceof String) {
                Method method = enumClass.getMethod("fromValue", String.class);
                return (E) method.invoke(null, value);
            } else if (value instanceof Integer) {
                Method method = enumClass.getMethod("fromIndex", int.class);
                return (E) method.invoke(null, value);
            }
        } catch (Exception e) {
            throw new SQLException("Failed to convert database value to enum: " + value, e);
        }
        throw new SQLException("Unsupported type for enum conversion: " + value.getClass().getName());
    }
}